 var express = require('express');
var router = express.Router();
const db = require('../db/db');
const common = require('../lib/common');
const fs=require('fs')
const path=require('path')

router.post('/login', function(req, res, next) {
  let {no,pwd,identifyCode,code} = req.body;
  if (identifyCode !== code.toString()){
    res.send({flag:false,msg:"验证码错误"})
  }else {
    let sql = `select * from students where No = '${no}'`;
    db(sql,function (err,result) {
      if (err){
        res.send({flag:false,msg:"登录失败"});
        throw err;
      }else {
        if(result[0] == null){
          res.send({flag:false,msg:"该账号不存在"});
        }else if(result[0].pwd !== common.md5(pwd)){
          res.send({flag:false,msg:"密码不正确"});
        }else{
          req.session.no = no
          res.json({flag:true,msg:"登录成功！"})
        }
      }
    })
  }
});

router.post('/reg',function (req,res) {
  let {no,name,pwd,tel,email,major,role} = req.body;
  let sql = `select * from students where No = '${no}'`;
  db(sql,function (err,rows) {
    if (err){
      throw err;
    }else{
      if(rows.length !== 0){
        res.send({flag:false,msg:"该账号已经存在"});
      }else {
        sql = "insert into students(No,name,pwd,major_id,tel,`e-mail`,grade) values('" + no + "','" + name + "','" + common.md5(pwd) + "'," + "(SELECT CONCAT(Id) FROM major WHERE name = '" + major + "'),'" + tel + "','" + email + "','"  + role +"')"
        db(sql,function () {
          if (err){
            res.send({flag:false,msg:"注册失败"});
            throw err;
          }else {
            res.send({flag:true,msg:"注册成功"});
          }
        })
      }
    }
  })
});

router.get('/logout',function (req,res,next) {
  delete req.session.no;
  res.json({msg:"退出成功！"})
});

// router.get('/del/:id',function (req,res) {
//   let id=req.params.id;
//   let sql="delete from imgs where id="+id;
//   db(sql,function (err,result) {
//     if(err){
//       console.log('删除失败：'+err);
//       return;
//     }else{
//       res.redirect('/users/');
//     }
//   })
// })

router.post('/update',function (req,res,next) {
  let {pwd}=req.body;
  let no = req.session.no
  let sql=`update students set pwd = '${common.md5(pwd)}' where No=${no}`;
  db(sql,function (err,result) {
    if (err){
      res.send({flag:false,msg:"更新失败\n" + err});
    }else {
      res.send({flag:true,msg:"更新成功"});
    }
  })
});

router.post('/info', function(req, res, next) {
  let no = req.session.no
  let sql = `select No as no,students.name as name,tel,\`e-mail\` as email,major.name as major,grade
             from students,major
             where major.id = students.major_id and No = ${no}`;
  console.log(sql)
  db(sql,function (err,result) {
    if (err){
      res.send({flag:false,msg:"获取失败"});
      throw err;
    }else {
      res.json({flag:true,infoForm:result})
    }
  })
});

module.exports = router;
